package com.mind.adjust.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mind.adjust.domain.webservice.domain.ReCommitRequest;
import com.mind.api.WebServiceClient;
import com.mind.api.webservice.ShareCallbackResponse;
import com.mind.cache.lock.DistributedLock;
import com.mind.common.utils.DateUtils;
import com.mind.common.core.domain.AjaxResult;
import com.mind.system.domain.AjTicketTask;
import com.mind.adjust.domain.webservice.domain.Request;
import com.mind.adjust.domain.webservice.domain.Response;
import com.mind.adjust.service.AjTicketTaskService;
import com.mind.common.utils.StringUtils;
import com.mind.system.domain.vo.ShareCallBackVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/adjust/format/ticket")
@Log4j2
public class FormalTicketController {

    @Resource
    private WebServiceClient webServiceClient;
    @Resource
    private AjTicketTaskService ticketTaskService;
    @Resource
    private DistributedLock distributedLock;

    @PostMapping("/pushOrder")
    public Map<String, Response> pushOrder(@RequestBody @Validated Map<String, Request> params) throws Exception {
        //响应
        Map<String, Response> response = new HashMap<>(1);
        log.info("推单开始...,参数:{}", params);
        Request request = params.get("Request");
        List<AjTicketTask> ticketTaskList = ticketTaskService.selectByStatusList(request.getData().getTicketId(), Arrays.asList(1, 2));
        if (!CollectionUtils.isEmpty(ticketTaskList)) {
            log.error("{}, 推单失败：{}", request.getData().getTicketId(),"该单据存在未完成的任务，请稍后重试。");
            response.put("Response",
                    Response.createResponse(request.getHead().getBizTransactionId(), "0", "400", "该单据存在未完成的任务，请稍后重试。"));
            return response;
        }
        AjTicketTask oldTicketTask = ticketTaskService.selectLastVersionTask(request.getData().getTicketId());

//        if(oldTicketTask.set)
        int version = 1;
        try {
            if (oldTicketTask != null) {
                version = StringUtils.isNull(oldTicketTask.getVersion()) ? 1 : oldTicketTask.getVersion() + 1;
            }
            if (StringUtils.isNull(request.getData().getInfo().get("Basic"))) {
                log.error("推单失败：{}", "Data.Info.Basic is required");
                response.put("Response",
                        Response.createResponse("", "0", "400", "Data.Info.Basic is required."));
                return response;
            }
            Map<Object, Object> basic = (Map<Object, Object>) request.getData().getInfo().get("Basic");
//            if (StringUtils.isNull(basic.get("ebsOuCode"))) {
//                log.error("推单失败：{}", "Data.Info.Basic.ebsOuCode is required.");
//                response.put("Response",
//                        Response.createResponse("", "0", "400", "Data.Info.Basic.ebsOuCode is required."));
//                return response;
//            }
//            if(StringUtils.isNull(basic.get("sceneType"))){
//                log.error("推单失败：{}", "Data.Info.Basic.sceneType");
//                response.put("Response",
//                        Response.createResponse(request.getHead().getBizTransactionId(), "0", "400", "Data.Info.Basic.sceneType is required."));
//                return response;
//            }
            // 获取业务场景，业务大类，业务小类
            String businessMainCate = "";
            Map<Object, Object> detail = (Map<Object, Object>) request.getData().getInfo().get("Detail");
            Set<String> businessCateList = new HashSet<>();
            if (StringUtils.isNotNull(basic.get("sceneType"))) {
                businessCateList.add(basic.get("sceneType").toString());
            }
            if (StringUtils.isNotNull(basic.get("mainBizCatId"))) {
                businessMainCate = basic.get("mainBizCatId").toString();
            }
            if(StringUtils.isNotNull(detail)){
                Object feedetails = detail.get("feedetails");
                if(StringUtils.isNotNull(feedetails)){
                    JSONArray feedetailArray = JSONArray.parseArray(JSON.toJSONString(feedetails));
                    if(!CollectionUtils.isEmpty(feedetailArray)){
                        for(int i=0;i<feedetailArray.size();i++){
                            JSONObject feedetail = feedetailArray.getJSONObject(i);
                            if(StringUtils.isNotNull(feedetail.get("subBizCatId")))
                                businessCateList.add(feedetail.get("subBizCatId").toString());
                        }
                    }
                }
            }
            int finalVersion = version;
            String finalBusinessMainCate = businessMainCate;
            ticketTaskService.insertTicketTask(new AjTicketTask() {{
                setTicketId(request.getData().getTicketId());
                if (StringUtils.isNotNull(basic.get("applicationDate"))) {
                    setApplyDate(DateUtils.parseDate(basic.get("applicationDate").toString()));
                }
                if (StringUtils.isNotNull(basic.get("eBillPartyName"))) {
                    setApplyPerson(basic.get("eBillPartyName").toString());
                }
                if (StringUtils.isNotNull(basic.get("eBillDeptName"))) {
                    setApplyDept(basic.get("eBillDeptName").toString());
                }
                if (StringUtils.isNotNull(basic.get("eBillOrgName"))) {
                    setApplyComp(basic.get("eBillOrgName").toString());
                }
                if(StringUtils.isNotEmpty(finalBusinessMainCate)){
                    setBusinessMainCate(finalBusinessMainCate);
                }
                if(basic.get("ebsOuCode") != null) {
                    setOrgId(basic.get("ebsOuCode").toString());
                }
                // 产品需求
                if(StringUtils.isNotNull(basic.get("部门名称"))){
                    setApplyDept(basic.get("部门名称").toString());
                }
                setVersion(finalVersion);
                if (!CollectionUtils.isEmpty(businessCateList)) {
                    setBusinessCate(StringUtils.join(businessCateList, ","));
                }
                setTicketType(request.getData().getTicketType());
                setInfo(JSON.toJSONString(request.getData().getInfo()));
                setTriggerType(0);
                setStatus(1);
                setHandleResult(1);
            }});
            log.info("推单成功");
        } catch (Exception e) {
            log.error("推单时单据出现错误：", e);
            response.put("Response",
                    Response.createResponse("", "0", "500", "未知异常，请联系管理员！"));
            return response;
        }
        //成功时响应
        response.put("Response",
                Response.createResponse("", "1", "0", ""));
        return response;
    }

    @PostMapping("/reCommit")
    public Map<String, Response> reCommit(@RequestBody @Validated Map<String, ReCommitRequest> params) throws Exception {
        //响应
        Map<String, Response> response = new HashMap<>(1);
        ReCommitRequest request = params.get("Request");
        log.info("重新推单开始...,参数:{}", params);
        if (request == null) {
            log.error("重新推单失败：{}", "Request is required.");
            response.put("Response", Response.createResponse("0", "400", "Request is required."));
            return response;
        }
        List<AjTicketTask> ticketTaskList = ticketTaskService.selectByStatusList(request.getData().getTicketId(), Arrays.asList(1, 2));
        if (!CollectionUtils.isEmpty(ticketTaskList)) {
            log.error("重新推单失败：{}", "该单据存在未完成的任务，请稍后重试。");
            response.put("Response",
                    Response.createResponse("", "0", "400", "该单据存在未完成的任务，请稍后重试。"));
            return response;
        }
        AjTicketTask oldTicketTask = ticketTaskService.selectLastVersionTask(request.getData().getTicketId());


        int version = 1;
        if (oldTicketTask != null) {
            // 20250323 增加分布式锁删除
            this.distributedLock.tryUnlock(oldTicketTask.getTicketId());
            version = StringUtils.isNull(oldTicketTask.getVersion()) ? 1 : oldTicketTask.getVersion() + 1;
        }
        try {
            int finalVersion = version;
            ticketTaskService.insertTicketTask(new AjTicketTask() {{
                setTicketId(oldTicketTask.getTicketId());
                setTicketType(oldTicketTask.getTicketType());
                setVersion(finalVersion);
                setBusinessCate(oldTicketTask.getBusinessCate());
                setBusinessMainCate(oldTicketTask.getBusinessMainCate());
                setInfo(oldTicketTask.getInfo());
                setOrgId(oldTicketTask.getOrgId());
                setApplyDate(oldTicketTask.getApplyDate());
                setApplyPerson(oldTicketTask.getApplyPerson());
                setApplyDept(oldTicketTask.getApplyDept());
                setApplyComp(oldTicketTask.getApplyComp());
                setTriggerType(0);
                setRemark(request.getData().getTriggerType()==null?"":request.getData().getTriggerType());
                setStatus(1);
                setCallbackStatus(oldTicketTask.getCallbackStatus());
                setHandleResult(1);
            }});
            log.info("重新推单成功");
        } catch (Exception e) {
            log.error("重新推单出现错误：", e);
            response.put("Response",
                    Response.createResponse("", "0", "500", "未知异常，请联系管理员！"));
            return response;
        }
        //成功时响应
        response.put("Response",
                Response.createResponse("", "1", "0", ""));
        return response;
    }


}
